// pages/order/order.js
import { orderApi, addressApi, cartApi } from '../../utils/api.js'
import { checkLoginAndRedirect } from '../../utils/auth.js'
import { formatPrice, formatAddress } from '../../utils/format.js'
import { DELIVERY_STATUS, TABLEWARE_STATUS, PAY_METHOD } from '../../utils/constants.js'

const app = getApp()

Page({
  data: {
    loading: true,
    cartItems: [],
    selectedAddress: null,
    orderData: {
      deliveryStatus: DELIVERY_STATUS.IMMEDIATE,
      estimatedDeliveryTime: '',
      tablewareStatus: TABLEWARE_STATUS.BY_MEAL,
      tablewareNumber: 1,
      packAmount: 2,
      payMethod: PAY_METHOD.WECHAT,
      remark: ''
    },
    totalAmount: 0,
    packAmount: 2,
    showTimePicker: false,
    showPayMethodPicker: false,
    payMethodOptions: [
      { value: PAY_METHOD.WECHAT, label: '微信支付' },
      { value: PAY_METHOD.ALIPAY, label: '支付宝' }
    ]
  },

  onLoad() {
    this.initPage()
  },

  onShow() {
    // 检查是否有选中的地址
    this.checkSelectedAddress()
  },

  // 初始化页面
  async initPage() {
    if (!checkLoginAndRedirect()) {
      this.setData({ loading: false })
      return
    }

    try {
      this.setData({ loading: true })
      
      // 并行加载购物车和默认地址
      const [cartRes, addressRes] = await Promise.all([
        cartApi.getList(),
        addressApi.getDefault()
      ])
      
      if (cartRes.code === 1) {
        const cartItems = cartRes.data || []
        this.setData({ cartItems })
        this.calculateTotal()
      }
      
      if (addressRes.code === 1) {
        this.setData({
          selectedAddress: addressRes.data
        })
      }
      
      // 设置默认配送时间
      this.setDefaultDeliveryTime()
      
    } catch (error) {
      console.error('初始化页面失败:', error)
      wx.showToast({
        title: '加载失败',
        icon: 'none'
      })
    } finally {
      this.setData({ loading: false })
    }
  },

  // 检查选中的地址
  checkSelectedAddress() {
    const pages = getCurrentPages()
    const currentPage = pages[pages.length - 1]
    
    // 如果从地址选择页面返回，更新选中的地址
    if (currentPage.selectedAddress) {
      this.setData({
        selectedAddress: currentPage.selectedAddress
      })
      // 清除临时数据
      delete currentPage.selectedAddress
    }
  },

  // 设置默认配送时间
  setDefaultDeliveryTime() {
    const now = new Date()
    const deliveryTime = new Date(now.getTime() + 30 * 60 * 1000) // 30分钟后
    
    const timeString = deliveryTime.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    }).replace(/\//g, '-')
    
    this.setData({
      'orderData.estimatedDeliveryTime': timeString
    })
  },

  // 计算总价
  calculateTotal() {
    const { cartItems, packAmount } = this.data
    let totalAmount = 0
    
    cartItems.forEach(item => {
      totalAmount += item.amount * item.number
    })
    
    totalAmount += packAmount
    
    this.setData({
      totalAmount: formatPrice(totalAmount)
    })
  },

  // 选择地址
  selectAddress() {
    wx.navigateTo({
      url: '/pages/address/address?from=order'
    })
  },

  // 切换配送方式
  toggleDeliveryStatus() {
    const { orderData } = this.data
    const newStatus = orderData.deliveryStatus === DELIVERY_STATUS.IMMEDIATE 
      ? DELIVERY_STATUS.SCHEDULED 
      : DELIVERY_STATUS.IMMEDIATE
    
    this.setData({
      'orderData.deliveryStatus': newStatus
    })
    
    if (newStatus === DELIVERY_STATUS.SCHEDULED) {
      this.setData({
        showTimePicker: true
      })
    }
  },

  // 选择配送时间
  selectDeliveryTime(e) {
    const { value } = e.detail
    this.setData({
      'orderData.estimatedDeliveryTime': value,
      showTimePicker: false
    })
  },

  // 切换餐具状态
  toggleTablewareStatus() {
    const { orderData } = this.data
    const newStatus = orderData.tablewareStatus === TABLEWARE_STATUS.BY_MEAL 
      ? TABLEWARE_STATUS.BY_COUNT 
      : TABLEWARE_STATUS.BY_MEAL
    
    this.setData({
      'orderData.tablewareStatus': newStatus
    })
  },

  // 调整餐具数量
  adjustTablewareNumber(e) {
    const { type } = e.currentTarget.dataset
    const { orderData } = this.data
    let newNumber = orderData.tablewareNumber
    
    if (type === 'increase') {
      newNumber += 1
    } else if (type === 'decrease' && newNumber > 1) {
      newNumber -= 1
    }
    
    this.setData({
      'orderData.tablewareNumber': newNumber
    })
  },

  // 显示支付方式选择器
  showPayMethodSelector() {
    this.setData({
      showPayMethodPicker: true
    })
  },

  // 选择支付方式
  selectPayMethod(e) {
    const { value, label } = e.currentTarget.dataset
    this.setData({
      'orderData.payMethod': value,
      showPayMethodPicker: false
    })
  },

  // 输入备注
  onRemarkInput(e) {
    this.setData({
      'orderData.remark': e.detail.value
    })
  },

  // 表单验证
  validateForm() {
    const { selectedAddress, cartItems } = this.data
    
    if (!selectedAddress) {
      wx.showToast({
        title: '请选择收货地址',
        icon: 'none'
      })
      return false
    }
    
    if (cartItems.length === 0) {
      wx.showToast({
        title: '购物车为空',
        icon: 'none'
      })
      return false
    }
    
    return true
  },

  // 提交订单
  async submitOrder() {
    if (!checkLoginAndRedirect()) return
    
    if (!this.validateForm()) return
    
    try {
      wx.showLoading({ title: '提交中...' })
      
      const { selectedAddress, cartItems, orderData, packAmount } = this.data
      
      // 计算总金额
      let totalAmount = 0
      cartItems.forEach(item => {
        totalAmount += item.amount * item.number
      })
      totalAmount += packAmount
      
      const orderParams = {
        addressBookId: selectedAddress.id,
        amount: totalAmount,
        deliveryStatus: orderData.deliveryStatus,
        estimatedDeliveryTime: orderData.estimatedDeliveryTime,
        packAmount: packAmount,
        payMethod: orderData.payMethod,
        remark: orderData.remark,
        tablewareNumber: orderData.tablewareNumber,
        tablewareStatus: orderData.tablewareStatus
      }
      
      const res = await orderApi.submit(orderParams)
      
      if (res.code === 1) {
        wx.showToast({
          title: '订单提交成功',
          icon: 'success'
        })
        
        // 清空购物车
        await cartApi.clear()
        
        // 跳转到订单详情页面
        setTimeout(() => {
          wx.redirectTo({
            url: `/pages/order-detail/order-detail?id=${res.data.id}`
          })
        }, 1500)
      } else {
        throw new Error(res.msg || '提交失败')
      }
    } catch (error) {
      console.error('提交订单失败:', error)
      wx.showToast({
        title: error.message || '提交失败',
        icon: 'none'
      })
    } finally {
      wx.hideLoading()
    }
  },

  // 取消选择器
  cancelPicker() {
    this.setData({
      showTimePicker: false,
      showPayMethodPicker: false
    })
  },

  // 设置选中的地址（从地址选择页面返回时调用）
  setSelectedAddress(address) {
    this.setData({
      selectedAddress: address
    })
  }
})
